package com.njmaomao.gj.pyot.domain.yto;

import com.njmaomao.gj.pyot.common.XmlUtil;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.stream.Collectors;

@Slf4j
public class YtApiService {

    @Autowired
    private RestTemplate restTemplate;

    public <Resp, Req> Resp ytpost(String url, Req req, Class<Resp> respClass, String partnerId, String clientId, String type) {

        String logisticsInterface = XmlUtil.objectToXml(req);
        MultiValueMap<String, String> params= new LinkedMultiValueMap<>();
        params.add("logistics_interface", logisticsInterface);
        params.add("data_digest", base64(MD5(logisticsInterface + partnerId)));
        params.add("clientId", clientId);
        params.add("type", type);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("accept", "*/*");
        headers.add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

        String paramStr = params.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue().get(0)).collect(Collectors.joining("&"));
        log.info("YtApiService.ytpost url:{}, paramStr:{}", url, paramStr);
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, headers);

        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);

        String body = responseEntity.getBody();
        log.info("YtApiService.ytpost url:{}, resp: {}", url, body);
        return XmlUtil.xml2Bean(body, respClass);
    }


    /**
     * MD5加密
     */
    protected byte[] MD5(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            log.error("MD5 error: " + str, e);
        }
        byte[] bytes = md5.digest(str.getBytes());
        return bytes;
    }


    /**
     * base64编码
     */
    protected String base64(byte[] str) {
        return Base64.encode(str);
    }


    /*
        编码转换
     */
    protected String urlEncoder(String str, String charset) {
        String result = null;
        try {
            result = URLEncoder.encode(str, charset);
        } catch (UnsupportedEncodingException e) {
            log.error("urlEncoder error: str[" + str + "] charset:" + charset, e);
        }
        return result;
    }

    /**
     * 签名生成
     */
    protected String encrypt(String logistics_interface, String partnerId, String charset) {
        /*if (partnerId != null) {
            return urlEncoder(base64(MD5(logistics_interface + partnerId)), charset);
        }*/
        return urlEncoder(base64(MD5(logistics_interface + partnerId)), charset);
    }

    /*public static void main(String[] args) {
        String logisticsInterface = "<order></order>";
        YtoApiService ytoApiService = new YtoApiService();
        System.out.println(ytoApiService.urlEncoder(logisticsInterface, "UTF-8").equals("%3Corder%3E%3C%2Forder%3E"));
        System.out.println(ytoApiService.encrypt(logisticsInterface, ytoApiService.partnerId, "UTF-8").equals("LghTkEmsD2tbQ3fsIBRcBg%3D%3D"));
    }*/

}
